package com.amuji.adiaosexpense;

import java.util.List;
import java.util.Random;

import com.amuji.adiaosexpense.db.PersonsDataSource;
import com.amuji.adiaosexpense.domainObjs.Person;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;

public class Overview extends ListActivity  {

  private PersonsDataSource datasource;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overview);

    datasource = new PersonsDataSource(this);
    datasource.open();

    List<Person> values = datasource.getAll();

    // Use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this,
        android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
  }

  // Will be called via the onClick attribute
  // of the buttons in main.xml
  public void onClick(View view) {
    @SuppressWarnings("unchecked")
    ArrayAdapter<Person> adapter = (ArrayAdapter<Person>) getListAdapter();
    Person person = null;
    switch (view.getId()) {
    case R.id.add:
      String[] names = new String[] { "Cool", "Very nice", "Hate it" };
      // Save the new comment to the database
      Person personToSave = new Person();
      personToSave.setFirstName(names[new Random().nextInt(3)]);
      personToSave.setLastName(names[new Random().nextInt(3)]);
      person = datasource.createPerson(personToSave);
      adapter.add(person);
      break;
    case R.id.delete:
      if (getListAdapter().getCount() > 0) {
        person = (Person) getListAdapter().getItem(0);
        datasource.delete(person);
        adapter.remove(person);
      }
      break;
    }
    adapter.notifyDataSetChanged();
  }

  @Override
  protected void onResume() {
    datasource.open();
    super.onResume();
  }

  @Override
  protected void onPause() {
    datasource.close();
    super.onPause();
  }
}
